package engine.systems.spatial.path
{
	import ash.core.Entity;
	
	import ash.core.Component;
	
	import flash.geom.Point;
	
	import org.osflash.signals.Signal;
	
	public class Path extends Component
	{
		internal var invalidate:Boolean = false;
		
		private var _active:Boolean;
		public var forward:Boolean;
		public var loop:Boolean;
		
		private var _points:Array;
		private var _index:int;
		
		public var complete:Signal = new Signal(Entity);
		
		public function Path(points:Array = null, index:int = 0, active:Boolean = true, forward:Boolean = true, loop:Boolean = false)
		{
			this.points 	= points;
			this.index 		= index;
			
			this.active 	= active;
			this.forward 	= forward;
			this.loop 		= loop;
		}
		
		override public function destroy():void
		{
			this.complete.removeAll();
			this.complete = null;
			
			while(this._points.length > 0)
			{
				var point:Point = this._points.pop();
				point = null;
			}
			this._points = null;
		}
		
		public function get active():Boolean { return this._active; }
		public function set active(active:Boolean):void
		{
			if(!this._points || this._points.length <= 0) return;
			
			if(active) this.invalidate = true;
			
			this._active = active;
		}
		
		public function get index():int { return this._index; }
		public function set index(index:int):void
		{
			if(!this._points || this._points.length <= 0) return;
			
			if(this._index == index) return;
			
			if(this.loop)
			{
				if(index < 0) 								index = this._points.length - 1;
				else if(index > this._points.length - 1) 	index = 0;
			}
			else
			{
				if(index < 0)
				{
					index = 0;
					this.active = false;
				}
				else if(index > this._points.length - 1)
				{
					index = this._points.length - 1;
					this.active = false;
				}
			}
			
			this._index = index;
		}
		
		public function get points():Array { return this._points; }
		public function set points(points:Array):void
		{
			this._points = points;
			
			if(!this._points || this._points.length <= 0)
			{
				this._active = false;
				this._index = 0;
			}
			else if(this._index > this._points.length - 1) this._index = this._points.length - 1;
		}
	}
}